package com.innodealing.consumer;

import com.innodealing.hermes.kafka.model.KafkaMessage;
import com.innodealing.hermes.kafka.util.DynamicKafkaListenerRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class DynamicKafkaListenerExample {

    @Autowired
    private DynamicKafkaListenerRegistry dynamicKafkaListenerRegistry;

    @PostConstruct
    public void init() {
        dynamicKafkaListenerRegistry.registerKafkaListener("dynamic_hermes_example", "dynamic-hermes-example-group", kafkaMessages -> {
            // 处理 Kafka 消息的业务逻辑
            System.out.println("接收到消息数: " + kafkaMessages.size());
            for (KafkaMessage kafkaMessage : kafkaMessages) {
                String value = kafkaMessage.getContent();
                try {
                    // 模拟业务处理逻辑
                    if (value.contains("error")) {
                        throw new RuntimeException("业务处理异常: " + value);
                    }
                    System.out.println("处理成功: " + value);
                } catch (Exception e) {
                    System.err.println("消息处理失败: " + value + ", 错误: " + e.getMessage());
                    throw e;
                }
            }
        });
    }
}
